package com.itheima.security;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.exceptions.BusinessException;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class SecurityUserService implements UserDetailsService {

    @Reference(version = "1.0.0")
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查找数据库中存在的用户对象
        com.itheima.pojo.User user = userService.findUserByUserName(username);

        if (user==null){
            //判断用户不存在，抛出业务异常
            throw  new BusinessException("用户不存在");
        }
        //创建集合用于存放用户的角色和权限
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        Set<Role> roleSet = user.getRoles();
        //遍历用户角色集合获取用户权限
        for (Role role : roleSet) {
            //赋予角色
            grantedAuthorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
            //获取角色拥有的权限并遍历
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //赋予权限
                grantedAuthorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        System.out.println(user);
        UserDetails userDetails = new User(username,user.getPassword(),grantedAuthorityList);
        user.setLoginCount(user.getLoginCount()+1);
        userService.updateLoginCount(user);
        return userDetails;
    }


}
